<template>
  <div class="cart-box">
    <header class="header">
      <div>&nbsp;&nbsp;&nbsp;</div>
      <div class="title">购物车</div>
      <van-icon name="weapp-nav" />
    </header>
    <div class="cart-body">
      <van-checkbox-group
        v-model="result"
        ref="checkboxGroup"
        @change="groupChange"
      >
        <van-swipe-cell v-for="item in list" :key="item.goodsId">
          <van-checkbox :name="item.cartItemId" />
          <van-card
            num="2"
            :price="item.sellingPrice"
            :title="item.goodsName"
            class="goods-card"
            :thumb="item.goodsCoverImg"
          >
            <template #footer>
              <van-stepper
                v-model="item.goodsCount"
                min="1"
                max="5"
                :name="item.cartItemId"
                @change="onChange"
              />
            </template>
          </van-card>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click="deleteGood(item.cartItemId)"
            />
          </template>
        </van-swipe-cell>
      </van-checkbox-group>
    </div>
    <van-submit-bar
      :price="totalPrice * 100"
      button-text="提交订单"
      @submit="onSubmit"
      class="submit-all"
    >
      <van-checkbox v-model="checkAll" @click="allCheck">全选</van-checkbox>
    </van-submit-bar>
    <Tabbar></Tabbar>
  </div>
</template>

<script>
import Tabbar from "../components/Tabbar.vue";
import { onMounted, toRefs, reactive, computed } from "vue";
import { Toast } from "vant";
import { useStore } from "vuex";
import { getCart, ModifyCart, deleteCartItem } from "../service/cart";
import {useRouter} from 'vue-router'
export default {
  components: {
    Tabbar,
  },
  setup() {
    const router = useRouter()
    const store = useStore();
    const state = reactive({
      list: [],
      result: [],
      checkAll: true,
    });
    onMounted(() => {
      init();
    });
    // 加载购物车数据
    const init = async () => {
      Toast.loading({ message: "商品加载中", forbidClick: true });
      const { data } = await getCart({ pageNumber: 1 });
      state.list = data;
      state.result = data.map((item) => item.cartItemId);
      console.log(state.list, state.result);
      Toast.clear();
    };

    //  修改数量
    const onChange = async (value, detail) => {
      Toast.loading({ message: "修改中", forbidClick: true });
      console.log(value, detail);
      const params = {
        cartItemId: detail.name,
        goodsCount: value,
      };
      await ModifyCart(params);
      Toast.clear();
    };

    // 删除商品
    const deleteGood = async (id) => {
      Toast.loading({ message: "删除中", forbidClick: true });
      await deleteCartItem(id);
      store.dispatch("updateCart");
      Toast.clear;
      init();
    };

    // 全选
    const allCheck = () => {
      console.log(state.result);
      if (!state.checkAll) {
        // 要全部不选中
        state.result = [];
      } else {
        state.result = state.list.map((item) => item.cartItemId);
      }
    };

    // 单选
    const groupChange = () => {
      state.checkAll =
        state.result.length == state.list.map((item) => item.cartItemId).length
          ? true
          : false;
    };

    const totalPrice = computed(() => {
      let sum = 0;
      let _list = state.list.filter((item) =>
        state.result.includes(item.cartItemId)
      );

      for (let item of _list) {
        sum += item.goodsCount * item.sellingPrice;
      }
      return sum;
    });

    const onSubmit = () => {
      router.push({ path: '/order', query: { cartItemIds: JSON.stringify(state.result)}})
    }

    return {
      state,
      ...toRefs(state),
      onChange,
      deleteGood,
      allCheck,
      groupChange,
      totalPrice,
      onSubmit
    };
  },
};
</script>

<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  font-size: 15px;
  height: 30px;
  align-items: center;
  border-bottom: 1px solid #dcdcdc;
}

.delete-button {
  right: -1px !important;
}

</style>
<style lang="less" scoped>
.cart-box {
  .cart-body {
    margin: 16px 0 100px 0;
    padding-left: 10px;
  }
}
</style>
<style>
.van-checkbox {
  width: 22px;
}
.van-swipe-cell__wrapper {
  display: flex;
}
.van-card.goods-card {
  width: 100%;
  background-color: #fff;
}
.delete-button {
  height: 100%;
}
.van-card__footer {
  position: absolute;
  right: 16px;
  bottom: 8px;
}
.van-card__price {
  color: red;
  font-size: 16px;
}
.submit-all {
  bottom: 50px;
}
.checkAll {
  width: 60px;
}
</style>